package freighttmpl

import (
	"context"
	"strconv"

	"mall/common/modelx"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetFreightTemplateByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetFreightTemplateByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetFreightTemplateByIdLogic {
	return &BackendGetFreightTemplateByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: freighttmpl
func (l *BackendGetFreightTemplateByIdLogic) BackendGetFreightTemplateById(
	in *setting.FreightTemplateIdReq,
) (*setting.FreightTemplateInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.FreightTemplate.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var restrictions []*setting.FreightTemplateRestrictionInfo
	if in.WithRestrictions != nil && *in.WithRestrictions > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysFreightTemplateRestrictionColumns.TemplateID] = map[string][]any{
			"equalTo": []any{in.Id},
		}
		list, _, err := l.svcCtx.FreightTemplate.GetRestrictionList(l.ctx, model.M{
			"orderBy": model.SysFreightTemplateRestrictionColumns.Sort + " DESC",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				var threshold string
				switch v.Mode {
				case enum.FreightTemplateRestrictionAmount:
					threshold = moneyx.FormatAmount(int64(v.Threshhold))
				case enum.FreightTemplateRestrictionNumber:
					threshold = strconv.FormatInt(int64(v.Threshhold), 10)
				}
				var regions *string
				if v.Regions.Valid {
					regions = pointy.GetPointer(string(v.Regions.JSON))
				}
				restrictions = append(restrictions, &setting.FreightTemplateRestrictionInfo{
					Id:         &v.RestrictionID,
					TemplateId: &v.TemplateID,
					Regions:    regions,
					Mode:       pointy.GetPointer(uint32(v.Mode)),
					Threshold:  &threshold,
					Sort:       pointy.GetPointer(uint32(v.Sort)),
					Status:     pointy.GetPointer(uint32(v.Status)),
				})
			}
		}
	}

	var rules []*setting.FreightTemplateRuleInfo
	if in.WithRules != nil && *in.WithRules > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysFreightTemplateRuleColumns.TemplateID] = map[string][]any{
			"equalTo": []any{in.Id},
		}
		filterMap[model.SysFreightTemplateRuleColumns.ChargeMode] = map[string][]any{
			"equalTo": []any{res.ChargeMode},
		}
		list, _, err := l.svcCtx.FreightTemplate.GetRuleList(l.ctx, model.M{
			"orderBy": model.SysFreightTemplateRuleColumns.Sort + " DESC",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				var regions *string
				if v.Regions.Valid {
					regions = pointy.GetPointer(string(v.Regions.JSON))
				}

				var firstUnit string
				var continueUnit string
				switch res.ChargeMode {
				case enum.FreightTemplateRuleNumber:
					firstUnit = strconv.FormatInt(int64(v.FirstUnit), 10)
					continueUnit = strconv.FormatInt(int64(v.ContinueUnit), 10)
				case enum.FreightTemplateRuleWeight:
					firstUnit = moneyx.FormatWeight(int64(v.FirstUnit))
					continueUnit = moneyx.FormatWeight(int64(v.ContinueUnit))
				case enum.FreightTemplateRuleVolume:
					firstUnit = moneyx.FormatVolume(int64(v.FirstUnit))
					continueUnit = moneyx.FormatVolume(int64(v.ContinueUnit))
				}

				firstPrice := moneyx.FormatAmount(int64(v.FirstPrice))
				continuePrice := moneyx.FormatAmount(int64(v.ContinuePrice))

				rules = append(rules, &setting.FreightTemplateRuleInfo{
					Id:            &v.RuleID,
					TemplateId:    &v.TemplateID,
					Regions:       regions,
					ChargeMode:    pointy.GetPointer(uint32(v.ChargeMode)),
					FirstUnit:     &firstUnit,
					FirstPrice:    &firstPrice,
					ContinueUnit:  &continueUnit,
					ContinuePrice: &continuePrice,
					Sort:          pointy.GetPointer(uint32(v.Sort)),
					Status:        pointy.GetPointer(uint32(v.Status)),
				})
			}
		}
	}

	return &setting.FreightTemplateInfo{
		Id:           &res.ID,
		Name:         &res.Name,
		Remark:       &res.Remark,
		FreeShipping: pointy.GetPointer(uint32(res.FreeShipping)),
		ChargeMode:   pointy.GetPointer(uint32(res.ChargeMode)),
		Sort:         pointy.GetPointer(uint32(res.Sort)),
		Status:       pointy.GetPointer(uint32(res.Status)),
		CreatedAt:    pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:    pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:    pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Restrictions: restrictions,
		Rules:        rules,
	}, nil
}
